<?php

namespace app\home\controller;

use app\common\model\Goods;
use app\common\model\InquiryInfoModel;
use app\common\model\InquiryStationModel;
use app\common\model\Brand;
use app\common\model\Goodsclass;
use app\common\model\InquiryHistoryModel;
use app\common\model\InquiryModel;
use app\common\model\Storeclass;
use PHPExcel_IOFactory;
use think\Request;
use think\Lang;
use think\Db;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Sellerinquiry extends BaseSeller
{
    protected $template_dir;
    var $_store_id;
    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . "/sellergoodsadd.lang.php");
        Lang::load(APP_PATH . 'home/lang/' . config('default_lang') . '/sellerreturn.lang.php');
        $this->template_dir = 'default/seller/sellerinquiry/';
    }

    public function index()
    {
        $this->goods_list();
    }

    /**
     * 供列表
     */
    public function goods_list()
    {

        $inquiry_list = (new InquiryModel())->getInquiryList();
        $station = (new InquiryStationModel())->getStationByInquiryId(input('param.inquiry_id', 0));
        $config_list = InquiryInfoModel::$goodConfig;
        $inquiryInfoModel = new InquiryInfoModel();
        $condition = array();
        if (!empty(input('param.scheme_name'))) {
            $condition['info.scheme_name'] = array('like', "%" . input('param.scheme_name') . "%");
        }
        if (!empty(input('param.inquiry_id'))) {
            $condition['info.inquiry_id'] = input('param.inquiry_id');
        }
        if (!empty(input('param.station_id'))) {
            $condition['info.station_id'] = input('param.station_id');
        }
        if (!empty(input('param.config_id'))) {
            $condition['info.good_config'] = array('like', "%" . input('param.config_id') . "%");
        }
        if (!empty(input('param.keyword'))) {
            $condition['s.scheme_name'] = array('like', "%" . input('param.keyword') . "%");
        }
        if (input('param.configure') != '') {
            $condition['s.configure'] = input('param.configure');
        }
        $condition['s.member_id'] =  $_SESSION['home']['member_id'];
        $condition['s.is_del'] = 0;
        $info = $inquiryInfoModel->getSellerInquiryList($condition, 10);
        $this->assign('inquiry_list', $info);
        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('Sellerinquiry');
        $this->setSellerCurItem('sellerinquiry');
        echo $this->fetch($this->template_dir . 'index');
        exit;
    }


    /**
     * 我要询价
     */
    public function add_inquiry()
    {

        if (request()->isPost()) {
        } else {
            //获取店铺类型
            $store_type = db('inquiries')->where(['is_del' => 0])->select();

            //获取工位
            $station = db('inquiry_station')->where(['status' => 1, 'is_del' => 0])->select();

            $this->assign('store_type', $store_type);
            $this->assign('station', $station);
            return $this->fetch($this->template_dir . 'add_inquiry');
        }
    }

    public function import_inquiry()
    {

        $data = array(
            'scheme_name' => input('param.scheme_name', ''),
            'inquiry_id' => input('param.inquiry_id', ''),
            'station_id' => input('param.station_id', ''),
            'configure' => input('param.configure', ''),
            'remarks' => input('param.remarks', ''),
            'station_id' => input('param.add_station', ''),
            'member_id' => $_SESSION['home']['member_id'],
            'c_time' => time()
        );

        $inquiry_id = db('seller_inquiry')->insertGetId($data);


        #根据询价的配置来入库商品
        $station_info = db('inquiry_info')->where(['id'=>input('param.add_station', '')])->find();
        $parms = [
            'inquiry_id' => input('param.inquiry_id', ''),
            'station_id' => $station_info['station_id'],
            // 'good_config' => ['in',input('param.configure', '')]
        ];
        $inquiry_info = db('inquiry_info')->where($parms)->select();

        if (!empty($inquiry_info)) {
            $inquiry_goods = [];
            foreach ($inquiry_info as $k => $v) {
                // $goods_info = db('goods')->alias('g')
                //     ->join('brand b', 'b.brand_id = g.brand_id')
                //     ->where(['goods_id' => $v['goods_id']])
                //     ->find();
                $goods_info = db('goodscommon')->alias('g')
                    ->join('brand b', 'b.brand_id = g.brand_id')
                    ->where(['goods_commonid' => $v['goods_id']])
                    ->find();    
                $param = getClassNameInfo($goods_info['gc_id']);
                $inquiry_goods = [
                    'goods_id' => $v['goods_id'],
                    'goods_name' => $goods_info['goods_name'],
                    'goods_images' => $goods_info['goods_image'],
                    // 'spec_type' => $goods_info['spec_values'],
                    'class_id' => $goods_info['gc_id'],
                    'gc_name' => $param['class_name'],
                    'brand_id' => $goods_info['brand_id'],
                    'brand_name' => $goods_info['brand_name'],
                    'num' => $v['num'],
                    'inquiry_id' => $inquiry_id
                ];
                db('seller_inquiry_goods')->insertGetId($inquiry_goods);
            }
        }

        if ($inquiry_id >= 0) {
            return json(['url' => url('Sellerinquiry/index'), 'code' => 1, 'msg' => '生成方案成功']);
            // $this->success('生成方案成功');
        } else {
            // return json(['url' => url('Sellerinquiry/index'), 'code' => 1, 'msg' => '生成方案失败']);
            $this->error(lang('edit_fail'));
        }
    }


    /**
     * 详细页
     */
    public function detail()
    {
        //获取方案详情
        $inquiry_info = db('seller_inquiry')->alias('s')
            ->join('inquiries q', 'q.id = s.inquiry_id')
            ->field('s.*,q.inquiry_name')
            ->where(['s.id' => intval(input('param.id'))])->find();
        $this->assign('inquiry_info', $inquiry_info);
        /* 设置卖家当前菜单 */
        $this->setSellerCurMenu('Sellerinquiry');
        $this->setSellerCurItem('detail');
        return $this->fetch($this->template_dir . 'detail');
    }

    /**
     * @description: 动态获取工位  @MrLiu
     * @param InquiryStationModel $inquiryStationModel
     */
    public function get_station()
    {
        $inquiry_id = intval(input('param.inquiry_id'));
        $data = (new InquiryStationModel())->getStationByInquiryId($inquiry_id);

        if (empty($data)) {
            $this->error('请求数据为空！');
            throw new \Exception();
        }
        $this->success('请求成功', null, $data);
    }

    //商品管理
    public function sellergoods()
    {
        $brand_model = model('goodproject');
        if (request()->isPost()) {
            $data = [
                'project_title' => input('post.project_title'),
            ];
            $brand_validate = validate('Goodproject');
            if (!$brand_validate->scene('brand_add')->check($data)) {
                $this->error($brand_validate->getError());
            } else {
                $update_array = array();
                //上传图片
                $default_dir = BASE_UPLOAD_PATH . DS . ATTACH_PATH . '/membertag';
                $img = '';
                if (!empty($_FILES['project_images']['name'])) {
                    $file = request()->file('project_images');
                    $info = $file->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($default_dir);
                    if ($info) {
                        $img = $info->getFilename();
                    } else {
                        $this->error($file->getError());
                    }
                }

                $brand_info = $brand_model->getBrandInfo(array('project_id' => intval(input('post.project_id'))));

                $condition['project_id'] = input('post.project_id');
                $express_list = rkcache('goods', true);
                $update_array['goods_commonid'] = empty($express_list) ? $brand_info['goods_commonid'] : $express_list;
                $update_array['project_title'] = input('post.project_title');
                $update_array['project_describe'] = input('post.project_describe');
                $update_array['project_images'] = empty($img) ? $brand_info['project_images'] : $img;
                $update_array['status'] = input('post.status');
                $result = $brand_model->editBrand($condition, $update_array);
                dkcache('goods');
                if ($result) {
                    $this->log(lang('ds_add') . lang('brand_index_brand') . '[' . input('post.brand_name') . ']', 1);
                    $this->success('修改成功', url('Goodproject/index'));
                } else {
                    $this->error(lang('ds_common_save_fail'));
                }
            }
        } else {
            //方案id
            $id = input('param.id');

            $goods_name = input('param.keyword');
            $where = array();
            $where['inquiry_id'] = $id;

            if (!empty($goods_name)) {
                $where['goods_name'] = array('like', "%" . $goods_name . "%");
            }

            $goods_list = db('seller_inquiry_goods')->where($where)->select();
            $config = db('config')->where('code', 'qiniu_http')->find();

            $this->assign('http_name', $config['value']);
            $this->assign('goods_name', $goods_name);


            $this->assign('goods_list', $goods_list);
            $this->assign('inquiry_id', $id);
            /* 设置卖家当前菜单 */
            $this->setSellerCurMenu('Sellerinquiry');
            $this->setSellerCurItem('sellergoods');
            return $this->fetch($this->template_dir . 'projec_goods');
        }
    }


    /*
      选择绑定商品
     */
    public function add_goods()
    {

        $brand_model = model('goodproject');
        $inquiry_id = input('param.id');

        $goods_info = db('seller_inquiry_goods')->where(['inquiry_id' => $inquiry_id])->select();
        $goods = [];
        foreach ($goods_info as $k => $v) {
            $goods[] = $v['goods_id'];
        }
        $this->assign('goods', $goods);
        $this->assign('inquiry_id', $inquiry_id);
        if (request()->isPost()) {
            $data = input('post.goods_commonid/a');
            if (empty($data)) {
                dsLayerOpenSuccess('请选择需要导入的商品');
            }
            foreach ($data as $key => $value) {

                $goods_info = db('goods')->alias('g')
                    ->join('brand b', 'b.brand_id = g.brand_id')
                    ->where(['goods_id' => $value])
                    ->find();
                $param = getClassNameInfo($goods_info['gc_id']);
                $goods_data = [
                    'goods_id' => $value,
                    'goods_name' => $goods_info['goods_name'],
                    'goods_images' => $goods_info['goods_image'],
                    'spec_type' => $goods_info['spec_values'],
                    'class_id' => $goods_info['gc_id'],
                    'gc_name' => $param['class_name'],
                    'brand_id' => $goods_info['brand_id'],
                    'brand_name' => $goods_info['brand_name'],
                    'num' => 1,
                    'inquiry_id' => $inquiry_id
                ];
                $inquiry_goods_id = db('seller_inquiry_goods')->insertGetId($goods_data);
                $info[] = $inquiry_goods_id;
            }
            $goods = implode(",", $info);
            #更新到主表里面
            db('seller_inquiry')->where(['id' => $inquiry_id])->update(['goods_id' => $goods]);

            dsLayerOpenSuccess('添加成功');
        } else {
            /**
             * 处理商品分类
             */
            $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;

            $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
            $this->assign('gc_json', json_encode($gccache_arr['showclass']));
            $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));
            $this->assign('choose_gcid', $choose_gcid);
            // 品牌
            $brand_list = model('brand')->getBrandPassedList(array());

            $this->assign('brand_list', $brand_list);

            //三级分类查询
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id'=>0]);
            $this->assign('class_list',$parent_class_list);

            $name = input('param.search_brand_name');
            $where = array();
            if (!empty($name)) {
                $where['goodscommon.goods_name'] = array('like', "%" . $name . "%");
            }

            //分类查询
            $search_gc_id1 = input('get.search_gc_id1', '');
            $search_gc_id2 = input('get.search_gc_id2', '');
            $search_gc_id3 = input('get.search_gc_id3', '');
            if ($search_gc_id1) {
                $where['goodscommon.gc_id_1'] = ['eq', $search_gc_id1];
            }
            if ($search_gc_id2) {
                $where['goodscommon.gc_id_2'] = ['eq', $search_gc_id2];
            }
            if ($search_gc_id3) {
                $where['goodscommon.gc_id_3'] = ['eq', $search_gc_id3];
            }

            #未删除商品
            $goods_model = model('goods');
            $where['y_goods.is_del'] = 0;
            $where['goodscommon.goods_status'] = 1;
            $where['y_goods.store_id'] = session('store_id');

            $goods_list = $goods_model->getGoodsUnionLists($where, '*', 'goodscommon.goods_verify desc, goodscommon.goods_commonid desc', '', 10);
            $this->assign('goods_list', $goods_list);
            $this->assign('show_page', $goods_model->page_info->render());
            $this->assign('search_brand_name', trim(input('param.search_brand_name')));
            return $this->fetch($this->template_dir . 'add_goods');
        }
    }


    //删除商品
    public function goods_drop()
    {
        $inquiry_id = input('param.id');

        //判断这个id在不在绑定商品里面
        $goods = db('seller_inquiry_goods')->where(['id' => $inquiry_id])->delete();

        ds_json_encode(10000, lang('ds_common_del_succ'));
    }

    public function seller_drop(Request $request)
    {
        $id = $request->post('id');
        $res = Db::table('ds_seller_inquiry')->where('id', '=', $id)->delete();
        if ($res) {
            return json(['url' => url('Sellerinquiry/index'), 'code' => 0, 'message' => '删除成功']);
        }
        return json(['url' => url('Sellerinquiry/index'), 'code' => 1000, 'message' => '删除失败']);
    }

    /**
     *    栏目菜单
     */
    function getSellerItemList()
    {
        $item_list = array(
            array(
                'name' => 'sellerinquiry',
                'text' => '询价列表',
                'url' => url('Sellerinquiry/index'),
            ),
        );
        if (request()->action() === 'sellergoods') {
            $item_list = array(
                array(
                    'name' => 'sellerinquiry',
                    'text' => '询价列表',
                    'url' => url('Sellerinquiry/index'),
                ),
                array(
                    'name' => 'sellergoods',
                    'text' => '商品管理',
                    'url' => url('Sellerinquiry/sellergoods'),
                )
            );
        }

        return $item_list;
    }

    public function ajax_up_num(Request $request)
    {
        $id = $request->get('id', '0');
        $num = $request->get('num', '');
        if (empty($id)) {
            return json(['code' => 1000, 'message' => '参数错误']);
        }
        $res = db('seller_inquiry_goods')->where('id', '=', $id)->update(['num' => $num]);
        if ($res) {
            return json(['code' => 0, 'message' => '修改成功']);
        }

        return json(['code' => 1000, 'message' => '修改失败']);
    }

    /**
     * 导出
     *
     */
    public function export_step1()
    {
        $inquiry_list = (new InquiryModel())->getInquiryList();
        $station = (new InquiryStationModel())->getStationByInquiryId(input('param.inquiry_id', 0));
        $config_list = InquiryInfoModel::$goodConfig;
        $inquiryInfoModel = new InquiryInfoModel();
        $condition = array();
        if (!empty(input('param.scheme_name'))) {
            $condition['info.scheme_name'] = array('like', "%" . input('param.scheme_name') . "%");
        }
        if (!empty(input('param.inquiry_id'))) {
            $condition['info.inquiry_id'] = input('param.inquiry_id');
        }
        if (!empty(input('param.station_id'))) {
            $condition['info.station_id'] = input('param.station_id');
        }
        if (!empty(input('param.config_id'))) {
            $condition['info.good_config'] = array('like', "%" . input('param.config_id') . "%");
        }
        if (!empty(input('param.keyword'))) {
            $condition['s.scheme_name'] = array('like', "%" . input('param.keyword') . "%");
        }
        if (input('param.configure') != '') {
            $condition['s.configure'] = input('param.configure');
        }
        if (input('param.id') != '') {
            $condition['s.id'] = input('param.id');
        }
//        $condition['s.id'] = 2;
        $info = $inquiryInfoModel->getSellerInquiryList($condition, 10);
        $page = input('param.page', 1);
        $limit = input('param.limit', 15);
        //            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
        //            $limit2 = self::EXPORT_SIZE;
        //            $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', "{$limit1},{$limit2}");
        $this->createExcel($info);
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        require(EXTEND_PATH . "excel" . DS . 'phpExcel.php');
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_obj = new \PHPExcel();
        $excel_data = array();
        //设置样式
//        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
//        $excel_data[0][] = array('商品名称');
//        $excel_data[0][] = array('styleid' => 's_title', 'data' => '规格');
//        $excel_data[0][] = array('styleid' => 's_title', 'data' => '品牌');
//        $excel_data[0][] = array('styleid' => 's_title', 'data' => '价格');
//        $excel_data[0][] = array('styleid' => 's_title', 'data' => '数量');
        $inquiries_info= db('inquiries')->where('id',$data['0']['inquiry_id'])->find();
        if ($data['0']['configure'] == 1) {
            $configure_text = '低端配置';
        } else if ($data['0']['configure'] == 2) {
            $configure_text = '中端配置';
        } else {
            $configure_text = '高端配置';
        }
        $reate_time = date('Y-m-d H:i:s', $data['0']['c_time']);
        $excel_data[0] = array("方案名称：{$data['0']['scheme_name']}", "店铺类型：{$inquiries_info['inquiry_name']}", "配置类型：{$configure_text}", "创建时间：{$reate_time}", "备注：{$data['0']['remarks']}",);



        $excel_data[2] = ['商品名称', '规格', '品牌', '价格', '数量'];

        //data
        $k = 0;
        foreach ((array) $data as $k => $v) {
            // 获取商品信息
            $goods_ids = explode(',', $v['goods_id']);
            $where = array();
            $where['inquiry_id'] = $v['id'];
            $goods = db('seller_inquiry_goods')->where($where)->select();
            foreach ($goods as $vv) {
                $gg_ids[] = $vv['goods_id'];
            }
//            $goods = db('goods')->where('goods_id', 'in', $gg_ids)->join('goodscommon', 'goodscommon.goods_commonid = ds_goods.goods_id', 'left')->select();
//            dump($goods);exit;
            $i = 3;
            $nums = explode(',', $v['num']);
            foreach ($goods as $key => $val) {
                $gg = db('goods')->where('goods_id', '=', $val['goods_id'])->find();
                $excel_data[$i] = [$val['goods_name'], $val['gc_name'], $val['brand_name'], $gg['goods_price'], $val['num']];
//                $tmp = array();
//                $tmp[] = array('data' => $val['goods_name']);
//                $tmp[] = array('data' => $val['gc_name']);
//                $tmp[] = array('data' => $val['brand_name']);
//                $tmp[] = array('data' => $val['goods_price']);
//                if (isset($nums[$key])) {
//                    $num = $nums[$key];
//                } else {
//                    $num = 1;
//                }
//
//                $tmp[] = array('data' => $num);
//
//                $excel_data[$i] = $tmp;
                $i++;
            }
            $objSheet = $excel_obj->createSheet($k);
            $k++;

//            $objSheet = $excel_obj->getActiveSheet(); //获取当前活跃的sheet的操作对象
            $objSheet->setTitle($v['scheme_name']);//给当前的sheet创建名称
            $objSheet->fromArray($excel_data);


//            $excel_data = $excel_obj->charset($excel_data, CHARSET);
//            $excel_obj->addArray($excel_data);
//            $excel_obj->addWorksheet($excel_obj->charset($v['scheme_name'], CHARSET));
        }
        $objWriter = PHPExcel_IOFactory::createWriter($excel_obj, 'Excel2007');//参数写入

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename=导出询价.xlsx');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');

        //        $excel_obj->addWorksheet($excel_obj->charset('导出方案', CHARSET));
//        $objWriter->generateXML($excel_obj->charset('导出方案', CHARSET) . '-' . date('Y-m-d-H', time()));
    }
}
